<script>
import { uuid } from 'vue-uuid'
export default {
  name: 'LoginView',
  data () {
    return {
      kaptchaSrc: '',
      title: '机蜂博客登录',
      isLogin: true,
      isSend: false,
      sendBtnMsg: '60秒后重试...',
      inter: '',
      interSeconds: 60,
      showDialog: false,
      formData: {
        username: '',
        password: '',
        code: '',
        uuid: '',
        phone: '',
        confirmPassword: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空' }
          // { pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '用户名格式错误' }
        ],
        password: [
          { required: true, message: '密码不能为空' }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            validator: (rule, value, callback) => {
              if (value.length === 5) {
                callback()
              } else {
                callback(new Error('验证码长度错误！'))
              }
            }
          }
        ],
        phone: [
          { required: true, message: '手机号不能为空' },
          { pattern: /^1\d{10}$/, message: '手机号格式错误' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码' },
          {
            validator: (rule, value, callback) => {
              if (value === this.formData.password) {
                callback()
              } else {
                callback(new Error('两次密码不一致'))
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.loginFormRef.validate(valid => {
        if (valid) {
          this.$axios.post('login', this.formData).then(data => {
            this.$message.success('登录成功！')
            this.$cookies.set('token', data.token, '1d')
            this.$router.replace('/home')
          }).catch(() => {
            this.getKaptcha()
            this.formData.code = ''
          })
        }
      })
    },
    getKaptcha () {
      this.formData.uuid = uuid.v4()
      this.kaptchaSrc = process.env.VUE_APP_BASE_PATH + 'kaptcha.jpg?uuid=' + this.formData.uuid
    },
    register () {
      this.$refs.registerFormRef.validate(valid => {
        if (valid) {
          this.$axios.post('register', this.formData).then(() => {
            this.$alert('注册成功，请登录！', { type: 'success' }).then(() => {
              this.isLogin = true
            })
          }).catch(() => {})
        }
      })
    },
    forget () {
      this.$refs.forgetFormRef.validate(valid => {
        if (valid) {
          this.$axios.post('forget', this.formData).then(() => {
            this.$alert('修改密码成功，请登录！', { type: 'success' }).then(() => {
              this.isLogin = true
              this.showDialog = false
            })
          }).catch(() => {})
        }
      })
    },
    send (type) {
      let url = `register/send/${this.formData.phone}`
      if (type === 'forgetFormRef') {
        url = `forget/send/${this.formData.phone}`
      }
      this.$refs[type].validateField('phone', errorMessage => {
        if (!errorMessage) {
          this.$axios.post(url).then(data => {
            this.isSend = true
            this.$message.success('发送成功')
            this.formData.uuid = data.sid
            this.setInter()
          }).catch(e => e)
        }
      })
    },
    changeTime () {
      this.interSeconds--
      if (this.interSeconds === 0) {
        this.sendBtnMsg = '60秒后重试...'
        clearInterval(this.inter)
        this.isSend = false
        this.interSeconds = 60
      } else {
        this.sendBtnMsg = `${this.interSeconds < 10 ? '0' + this.interSeconds : this.interSeconds}秒后重试...`
      }
    },
    setInter () {
      this.inter = setInterval(() => {
        this.changeTime()
      }, 1000)
    }
  },
  created () {
    this.$nextTick(() => {
      this.getKaptcha()
    })
  },
  watch: {
    isLogin (newValue) {
      if (newValue) {
        this.title = '机蜂博客登录'
      } else {
        this.title = '注册用户'
      }
      this.formData = { ...this.$options.data().formData }
    },
    showDialog () {
      this.formData = { ...this.$options.data().formData }
    }
  }
}
</script>

<template>
<div class="content">
  <div class="login-group">
    <h3>{{title}}</h3>
    <el-form v-if="isLogin" key="login" ref="loginFormRef" :model="formData" :rules="rules" label-width="80px" @keydown.enter.native="login">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" prefix-icon="el-icon-user" clearable />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formData.password"
          placeholder="请输入密码"
          prefix-icon="el-icon-lock"
          type="password"
          clearable
          show-password/>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入验证码" prefix-icon="el-icon-bell" maxlength="5" clearable>
          <div slot="append" class="kaptcha-group">
            <img :src="kaptchaSrc" alt="验证码加载失败" title="点击切换图片" @click="getKaptcha">
          </div>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="login">登录</el-button>
        <el-button type="text" @click="isLogin = false">立即注册</el-button>
        <el-button type="text" @click="showDialog = true">忘记密码?</el-button>
      </el-form-item>
    </el-form>
    <el-form v-else key="register" ref="registerFormRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" prefix-icon="el-icon-user" clearable />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" prefix-icon="el-icon-mobile" clearable />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入验证码" prefix-icon="el-icon-bell" maxlength="5" clearable>
          <div slot="append" style="padding: 0 20px">
            <el-button :disabled="isSend" key="send" v-if="isSend">{{sendBtnMsg}}</el-button>
            <el-button v-else key="no-send" @click="send('registerFormRef')">发送短信</el-button>
          </div>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" placeholder="请输入密码" prefix-icon="el-icon-lock" type="password" clearable show-password/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" placeholder="请输入密码" prefix-icon="el-icon-lock" type="password" clearable show-password/>
      </el-form-item>
      <el-form-item>
        <el-button @click="register">注册</el-button>
        <el-button type="text" @click="isLogin = true">直接登录</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-dialog title="忘记密码" v-if="showDialog" :visible.sync="showDialog">
    <el-form key="forget" ref="forgetFormRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" prefix-icon="el-icon-mobile" clearable />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入验证码" prefix-icon="el-icon-bell" maxlength="5" clearable>
          <div slot="append" style="padding: 0 20px">
            <el-button :disabled="isSend" key="send" v-if="isSend">{{sendBtnMsg}}</el-button>
            <el-button v-else key="no-send" @click="send('forgetFormRef')">发送短信</el-button>
          </div>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" placeholder="请输入密码" prefix-icon="el-icon-lock" type="password" clearable show-password/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" placeholder="请输入密码" prefix-icon="el-icon-lock" type="password" clearable show-password/>
      </el-form-item>
      <el-form-item>
        <el-button @click="forget">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</div>
</template>
<style>
div[data-v-51b88ca4] .el-input-group__append{
  padding: 0;
}
</style>
<style scoped lang="scss">
.content{
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("@/assets/login-bg.jpg") no-repeat center/cover;
  /*在样式中直接再写的样式，默认是后代选择器*/
  .login-group{
    min-width: 500px;
    background-color: rgba(255,255,255,.4);
    padding:0 20px;
    border-radius: 20px;
    .kaptcha-group{
      height: 40px;
      width: 200px;
      img{
        display: block;
        height: 100%;
        width: 100%;
      }
    }
    /*在scss中使用&表示当前选择器：&:hover*/
    &>h3{
      text-align: center;
    }
  }
}
</style>
